package com.wwz.leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class LeetCode39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int length = candidates.length;
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        if (length == 0) {
            return ans;
        }
        dfs(candidates, target, ans, combine, 0);
        return ans;
    }

    // idx 很关键啊
    public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<Integer>(combine));
            return;
        }
        // 直接冲到末尾
        dfs(candidates, target, ans, combine, idx + 1);
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            combine.add(candidates[idx]);
            // idx不变 持续递归自己 直到不满足条件
            dfs(candidates, target - candidates[idx], ans, combine, idx);
            combine.remove(combine.size() - 1);
        }
    }

    @Test
    public void test() {
        System.out.println(combinationSum(new int[]{2, 3, 6, 7}, 7));
    }
}
